#include "Component/Item/Light/RoomLightComponent.h"

#include "Components/LightComponentBase.h"
#include "Subsystem/ItemManager/RoomLightManagerSubsystem.h"
#include "Subsystem/RoomManager/RoomManagerFunctionLibrary.h"

void URoomLightComponent::BeginPlay()
{
	Super::BeginPlay();

	// 收集所有灯组件相关的信息
	TArray<ULightComponentBase*> InLightComponents;
	GetOwner()->GetComponents(ULightComponentBase::StaticClass(), InLightComponents);
	LightComponents = InLightComponents;

	TurnOffLight(false);

	// 注册自己
	if (URoomLightManagerSubsystem* RoomLightManagerSubsystem = URoomManagerFunctionLibrary::GetRoomLightManagerSubsystem(this))
	{
		RoomLightManagerSubsystem->RegisterRoomLight(GetOwner());
	}
}

void URoomLightComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	// 取消注册自己
	if (URoomLightManagerSubsystem* RoomLightManagerSubsystem = URoomManagerFunctionLibrary::GetRoomLightManagerSubsystem(this))
	{
		RoomLightManagerSubsystem->UnregisterRoomLight(GetOwner());
	}

	// 清空灯组件信息
	LightComponents.Empty();

	Super::EndPlay(EndPlayReason);
}

void URoomLightComponent::TurnOnLight(bool bIsInit)
{
	LightOn(bIsInit);
	ReceiveLightOn(bIsInit);
	OnLightStateChanged.Broadcast(true, bIsInit);
}

void URoomLightComponent::TurnOffLight(bool bIsInit)
{
	ReceiveLightOff(bIsInit);
	LightOff(bIsInit);
	OnLightStateChanged.Broadcast(false, bIsInit);
}

void URoomLightComponent::LightOn(bool bIsInit)
{
	for (const TObjectPtr<ULightComponentBase> LightComponent : LightComponents)
	{
		LightComponent->SetVisibility(true, true);
	}
}

void URoomLightComponent::LightOff(bool bIsInit)
{
	for (const TObjectPtr<ULightComponentBase> LightComponent : LightComponents)
	{
		LightComponent->SetVisibility(false, true);
	}
}
